package com.bj58.groupbuy.action.service.impl;

import java.io.File;
import java.io.RandomAccessFile;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.bj58.groupbuy.action.db.CommonDao;
import com.bj58.groupbuy.action.db.DBConfig;
import com.bj58.groupbuy.action.model.AllianceBillingAttr;
import com.bj58.groupbuy.action.model.AllianceBillingMetrics;
import com.bj58.groupbuy.action.model.AllianceDataSummaryVo;
import com.bj58.groupbuy.action.model.AllianceDataSummaryVoForMail;
import com.bj58.groupbuy.action.model.ORKpiTarget;
import com.bj58.groupbuy.action.service.OnlineRevenueService;
import com.bj58.groupbuy.action.util.SomePublicUtil;
import com.bj58.groupbuy.util.PathUtil;
import com.bj58.groupbuy.wf.page.Paginate;

public class OnlineRevenueImpl implements OnlineRevenueService {
	private CommonDao comDao = new CommonDao();
	private SomePublicUtil spu = new SomePublicUtil();
	
	@Override
	public Paginate<AllianceBillingAttr> getAllianceBillingAttrList(
			String condition, int pageNum, int pageIndex) throws Exception {
		String countSql = "select count(1) from alliance_billing_attr where 1=1 "+condition;
		int count = comDao.countAll(countSql, 16);
		
		String searchSql = "select * from alliance_billing_attr where 1=1 "+condition;
		if(pageIndex >= 0){
			String limit ="limit "+(pageIndex-1)*pageNum+","+pageNum;//limit分页
			searchSql = searchSql+ " "+limit;
		}
		List<AllianceBillingAttr> rsList = comDao.getAllColsByVo(searchSql, AllianceBillingAttr.class, DBConfig.db_68_ors.getIntType());
		
		Paginate<AllianceBillingAttr> pList = new Paginate<AllianceBillingAttr>(count,pageIndex,pageNum,rsList);
		return pList;
	}

	
	@Override
	public int addNewAllianceBillingAttr(AllianceBillingAttr vo)
			throws Exception {
		List<String> cols = new ArrayList<String>();
		List<String> dicList = spu.getECDicByAnnotation(AllianceBillingAttr.class);
		for(String dic : dicList){
			cols.add(dic.split(",")[0]);
		}
		return comDao.insertOneByVo(cols, "alliance_billing_attr", AllianceBillingAttr.class, vo, DBConfig.db_68_ors.getIntType());
	}

	
	@Override
	public int updateAllianceBillingAttr(AllianceBillingAttr vo)
			throws Exception {
		return comDao.updateByVo("alliance_billing_attr", "id="+vo.getId(), AllianceBillingAttr.class, vo, DBConfig.db_68_ors.getIntType());
	}


	@Override
	public AllianceBillingAttr findAllianceBillingAttrById(int id)
			throws Exception {
		String searchSql = "select * from alliance_billing_attr where id= "+id;
		List<AllianceBillingAttr> rsList = comDao.getAllColsByVo(searchSql, AllianceBillingAttr.class, DBConfig.db_68_ors.getIntType());
		if(rsList.isEmpty() || null == rsList){
			return null;
		}
		return rsList.get(0);
	}


	@Override
	public Map<String,List<String>> getAllianceList() throws Exception {
		String searchSql = "SELECT source,allianceName FROM `alliance_billing_attr`  where  state = 1  group by source,allianceName";
		List<String> cols = new ArrayList<String>();
		cols.add("source");
		cols.add("allianceName");
		List<AllianceBillingAttr> rsList = comDao.getCommonStatList(searchSql, cols, AllianceBillingAttr.class, DBConfig.db_68_ors.getIntType());


		Map<String,List<String>> rsMap = new HashMap<String, List<String>>();
		
		for(AllianceBillingAttr vo : rsList){
			String key = vo.getSource();
			List<String> tempList = new ArrayList<String>();
			if(rsMap.containsKey(key)){
				tempList = rsMap.get(key);
			}
			tempList.add(vo.getAllianceName());
			rsMap.put(key, tempList);
		}
		return rsMap;
	}


	@Override
	public boolean inserABMList(List<AllianceBillingMetrics>  abmList ,String source)
			throws Exception {
			//写文件
			String filePath =PathUtil.getWFNamespaceFolder()+"/dbrecord/abmdata.txt";
			File file = new File(filePath);
			if(file.exists()){
				file.delete();
			}
			RandomAccessFile raf = new RandomAccessFile(file, "rw");
			StringBuffer content = new StringBuffer();
			
			Field[] fds = AllianceBillingMetrics.class.getDeclaredFields();
			Method[] mm = AllianceBillingMetrics.class.getMethods();
			Map<String,Method> methodMap = new HashMap<String,Method>();
			for(Method m: mm){
				methodMap.put(m.getName(), m);
			}
			for(AllianceBillingMetrics  vo : abmList){
				vo.setSource(source);
				for(int i = 0 ; i< fds.length ; i++){
					Field fd  = fds[i];
					String methodName = "get" + fd.getName().substring(0,1).toUpperCase()+fd.getName().substring(1);
					String value = "";
					if(null == methodMap.get(methodName).invoke(vo)){
						value ="";
					}else{
						value = methodMap.get(methodName).invoke(vo).toString();
					}
					if( (i+1) < fds.length ){
						content.append(value+"^&");
					}else{
						content.append(value+"\n");
					}
					
				}
			}
			raf.seek(raf.length());
			raf.write(content.toString().getBytes("UTF-8"));	
			raf.close();
			//load
			return comDao.loadData(filePath, "alliance_billing_metrics", "^&", DBConfig.db_68_ors.getIntType());
	}


	@Override
	public boolean deleteABMList(String condition) throws Exception {
		return  comDao.deleteData("alliance_billing_metrics", condition, DBConfig.db_68_ors.getIntType());
	}


	@Override
	public List<AllianceDataSummaryVoForMail> ORIncomeData(String condition)
			throws Exception {
		String sql = "select * from online_revenue_day where "+condition;
		List<AllianceDataSummaryVoForMail> rsList =  comDao.getAllColsByVo(sql, AllianceDataSummaryVoForMail.class, DBConfig.db_68_ors.getIntType());
		if(!rsList.isEmpty() && rsList != null){
			return rsList;
		}
		return null;
	}
	
	
	@Override
	public List<AllianceDataSummaryVoForMail> ORIncomeSumData(String condition)
			throws Exception {
		String sql = "select *select*  from online_revenue_day where "+condition;
		
		StringBuffer select = new StringBuffer();
		Field[]  fds = AllianceDataSummaryVo.class.getDeclaredFields();
		for(int i = 0 ; i < fds.length ; i++){
			Field fd = fds[i];
			String colName  = fd.getName();
			if(!"statDate".equals(colName) ){
				colName = "sum("+colName+")";
			}
			if((i+1) < fds.length){
				colName = colName +"," ;
			}
			select.append(colName);
		}
		sql = sql.replace("*select*", select.toString());
		List<AllianceDataSummaryVoForMail> rsList =  comDao.getAllColsByVo(sql, AllianceDataSummaryVoForMail.class, DBConfig.db_68_ors.getIntType());
		if(!rsList.isEmpty() && rsList != null){
			return rsList;
		}
		return null;
	}


	@Override
	public ORKpiTarget getORKpiTarget(String month)
			throws Exception {
		String sql = "select * from or_kpi_target where month='"+month+"'";
		List<ORKpiTarget>  rsList = comDao.getAllColsByVo(sql, ORKpiTarget.class, DBConfig.db_68_ors.getIntType());
		if(!rsList.isEmpty()  && rsList != null){
			return rsList.get(0);
		}
		return null;
	}


	@Override
	public boolean deleteDaySummary(String startDate, String endDate)
			throws Exception {
		String condition = " and statDate >= '"+startDate+"' and statDate <='"+endDate+"' ";
		return comDao.deleteData("online_revenue_day", condition, DBConfig.db_68_ors.getIntType());
	}


	
	
}
